from typing import Union, List, Dict

from fastapi import FastAPI,status
from pydantic import BaseModel, EmailStr

app = FastAPI()


class UserIn(BaseModel):
    username: str
    password: str
    email: EmailStr
    full_name: Union[str, None] = None

class UserInDB(BaseModel):
    username: str
    hashed_password: str = None
    email: EmailStr
    full_name: Union[str, None] = None


'''
2.1 **user_in.dict()
'''
'''Pydantic 的 .dict()'''
user_in = UserIn(username="yinyu", password="secret", email="yinyu.doe@example.com")
user_dict = user_in.dict()
print(user_dict)

'''解包'''
user_db = UserInDB(**user_dict)
print(user_db)

'''额外关键字'''
user_dbb = UserInDB(**user_dict,hashed_password = "secret11")
print(user_dbb)


'''
2.2 减少重复代码
'''
class UserBase(BaseModel):
    username: str
    email: EmailStr
    full_name: Union[str, None] = None

class UserIn1(UserBase):
    password: str

class UserInDB1(UserBase):
    hashed_password: str



'''Union 或者 anyOf'''
class BaseItem(BaseModel):
    description: str
    type: str


class CarItem(BaseItem):
    type = "car"


class PlaneItem(BaseItem):
    type = "plane"
    size: int

items1 = {
    "item1": {"description": "All my friends drive a low rider", "type": "car"},
    "item2": {
        "description": "Music is my aeroplane, it's my aeroplane",
        "type": "plane",
        "size": 5,
    },
}

@app.get("/items/{item_id}", response_model=Union[PlaneItem, CarItem])
async def read_item(item_id: str):
    return items1[item_id]

'''
2.3 响应状态码
'''
@app.post("/items1/", status_code=201)
async def create_item(name: str):
    return {"name": name}

@app.post("/items2/", status_code=status.HTTP_201_CREATED)
async def create_item(name: str):
    return {"name": name}


if __name__ == '__main__':
    import uvicorn
    uvicorn.run(app, host="127.0.0.1", port=8000)
    pass